import Panel from "./../../elements/Panel";
import Header from "./../../components/Header";
import Modal from "./../../components/Modal/";
import {connect} from "react-redux";
import CONFIG from "./../../libs/config";
import {Lang, Fetch} from "./../../libs/";
import {URL, setTitle,md5Url} from "./../../libs/Url";
import Label from "./../../components/FormLabel";
import FormGroup from "./../../components/FormGroup";
import FormItem from "./../../components/FormItem";
import FormItemType from "./../../components/FormItemType";
import InputGroup from "./../../components/InputGroup";
import Selected from "./../../components/SelectItem";
import BreadcrumbNavigation from "./../../components/BreadcrumbNavigation";
import {fetch, fetchUser} from "../../actions";
import {SUBJECT, PAGE_SUBJECT} from "./../../actions/subject";

const AddNews = React.createClass({
    getInitialState(){

        const self = this;
        this.isUpdate = this.props.router.params.id;
        setTitle(this.isUpdate ? Lang.title.update_notice : Lang.title.new_notice);

        this.form = [
            {
                name: 'classid',
                label: Lang.NEWS_CREATE.label.class,
                value: '',
                required: true,
                tips: '',
                type: FormItemType.MODAL_CHECK_BOX,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'classifyid',
                label: Lang.NEWS_CREATE.label.category,
                value: '',
                tips: '',
                required: true,
                inits: [],
                type: FormItemType.SELECT,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'title',
                label: Lang.NOTICE_CREATE.label.title,
                placeholder: '',
                required: true,
                value: '',
                tips: '',
                type: FormItemType.INPUT,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : '该项必填',
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    });
                }
            },
            {
                name: 'summary',
                label: Lang.NOTICE_CREATE.label.content,
                placeholder: '',
                value: '',
                required: true,
                tips: '',
                type: FormItemType.EDITOR,
                onchange: function (index, content) {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                value: content,
                                tips: content.length ? '' : Lang.NEWS_CREATE.tip,
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    })
                }
            }
        ];

        // const isUpdate = this.props.router.params.id;
        return {
            open: false,
            selected: '',
            form: this.isUpdate ? [] : self.form,
            tips: {}
        }
    },
    setchange(index, content){
        const self = this;
        self.setState({
            form: [
                ...self.state.form.slice(0, index),
                Object.assign({}, self.state.form[index], {
                    value: content,
                    tips: content.length ? '' : Lang.NEWS_CREATE.tip,
                }),
                ...self.state.form.slice(index + 1),
            ]
        })
    },
    componentDidMount() {
        const self = this;
        if (this.props.router.params.id) {
            Fetch(URL.NOTICE_GET, {body: {announceid: this.props.router.params.id}})
                .then((res)=> {
                    let news_ = res.announce;
                    //console.log(res);
                    self.form = self.form.map(item=> {
                        if (item == 'classid') {
                            item.value = news_.classList.map(function (item) {
                                return item.classid;
                            }).toString();
                        } else {
                            item.value = news_[item.name];
                        }
                        return item;
                    });
                    console.log(self.form);
                    self.setState({
                        form: self.form,
                    });
                })
                .catch(e=> {
                    console.log(e);
                })
        }
        const {dispatch} = this.props;
        dispatch(fetchUser(SUBJECT.NOTICES_CATEGORY));
        dispatch(fetch({url: URL.NOTICE_CATEGORY_FIND}))
    },

    onsubmit(){
        const {dispatch, user} = this.props, isUpdate = this.props.router.params.id;
        const self = this;
        var form = {};
        const data_category = self.props[md5Url.NOTICE_CATEGORY_FIND] || {};
        (!data_category.list && (data_category.list = []));
        if (!data_category.list.length)return alert('分类数据不完善!');
        self.state.form.forEach((item, index)=> {
            if (item.required && item.value.length == 0) {
                // if()
                if (index == 0) {
                    console.log(item.classid);
                    form[item.name] = user['class'].map(item=> {
                        return item.classid;
                    }).toString();
                } else if (index == 1) {
                    form[item.name] = data_category.list[0].id;
                } else {
                    self.setState({
                        form: [
                            ...self.state.form.slice(0, index),
                            Object.assign({}, self.state.form[index], {
                                tips: Lang.NEWS_CREATE.tip,
                            }),
                            ...self.state.form.slice(index + 1),
                        ]
                    })
                }
            } else {
                if (index == 0) {
                    form[item.name] = item.value;
                    if (item.value.slice(0, 1) == ',') {
                        form[item.name] = item.value.slice(1);
                    } else if (item.value.slice(item.value.length) == ',') {
                        form[item.name] = item.value.slice(0, item.value.length - 1);
                    }

                } else {
                    form[item.name] = item.value;
                }

            }
        });
        if (Object.keys(form).length >= self.state.form.length) {
            // form.classid = form.classid.slice(1);
            if (form.classid.length - 1 == form.classid.lastIndexOf(',')) {
                form.classid = form.classid.slice(0, form.classid.length - 1);
            }
            form.url = URL.NEWS_ADD;
            if (isUpdate) {
                form.announceid = isUpdate;
            }
            Fetch(isUpdate ? URL.NOTICE_EDIT : URL.NOTICE_ADD, {method: 'POST', body: form})
                .then(data=> {
                    alert(isUpdate ? '更新成功!' : '创建成功!');
                    if (!isUpdate) {
                        self.props.router.push(CONFIG.MENUS_ABSOLUTE.NOTICES);
                    }
                })
                .catch(e=> {
                    alert(isUpdate ? '更新失败!' : '更新失败!');
                    console.log(e);
                })
        }
    },
    render(){
        const self = this;
        const {user, dispatch}  = this.props;
        const form = this.props[PAGE_SUBJECT.NOTICE_ADD].form;

        const data_category = self.props[md5Url.NOTICE_CATEGORY_FIND] || {};
        // console.log(data_category);
        (!data_category.list && (data_category.list = []));

        return (
            <div>
                <BreadcrumbNavigation navs={[
                    {url: CONFIG.MENUS_ABSOLUTE.HOME, label: Lang.menus.HOME},
                    {url: CONFIG.MENUS_ABSOLUTE.NOTICES, label: Lang.menus.NOTICE_LIST},
                    {label: this.isUpdate ? Lang.menus.NOTICE_UPDATE : Lang.menus.NOTICE_CREATE}
                ]}></BreadcrumbNavigation>
                <Panel>
                    <Header>{this.isUpdate ? Lang.menus.NOTICE_UPDATE : Lang.menus.NOTICE_CREATE}</Header>
                    <div className="form-horizontal">
                        {
                            self.state.form.map((item, index)=> {
                                if (item.type == FormItemType.MODAL_CHECK_BOX) {
                                    return <FormItem {...item} key={index}>
                                        <div className="homeword">
                                            {
                                                user.class.map((item_, idex)=> {
                                                    item_.checked = self.state.form[index].value.indexOf(item_.classid) > -1 ||
                                                        (!self.state.form[index].value.replace(',', '').length);
                                                    return <Selected onremove={()=> {
                                                        var v = ''
                                                        if (!self.state.form[index].value) {
                                                            v = user.class.map(ite=> {
                                                                    return ite.classid;
                                                                }).toString() + ',';
                                                        }
                                                        item.onchange(index, (v || self.state.form[index].value).replace(item_.classid + ',', ''));
                                                    }} key={idex} {...item_} />
                                                })
                                            }
                                            <button className="btn btn-default btn-sm " onClick={()=> {
                                                this.setState({open: true})
                                            }} type="button"><i className="fa fa-hand-o-up"></i> {Lang.NEWS_CREATE.set}
                                            </button>
                                        </div>
                                        <Modal open={self.state.open}>
                                            <Modal.Header onclose={()=> {
                                                self.setState({open: false, selected: ''})
                                            }
                                            }>{Lang.NEWS_CREATE.choose}</Modal.Header>
                                            <Modal.Body >
                                                <form className="form-horizontal">
                                                    <div className="form-group">
                                                        <label
                                                            className="col-sm-3 control-label">{Lang.NEWS_CREATE.grade}：</label>
                                                        <div className="col-sm-9">
                                                            {
                                                                user.class.map((item_, idex)=> {
                                                                    return (
                                                                        <label className="checkbox-inline" key={idex}>
                                                                            <input type="checkbox"
                                                                                   checked={(self.state.form[index].value.concat(self.state.selected)).indexOf(item_.classid) > -1}
                                                                                   onClick={(e)=> {
                                                                                       if (e.target.checked) {
                                                                                           self.setState({
                                                                                               selected: self.state.selected + item_.classid + ','
                                                                                           })
                                                                                       } else {
                                                                                           self.setState({
                                                                                               selected: self.state.selected.replace(item_.classid + ',', '')
                                                                                           });
                                                                                       }
                                                                                   }}/>
                                                                            {item_['class'].name} </label>
                                                                    )
                                                                })
                                                            }
                                                        </div>
                                                    </div>
                                                </form>
                                            </Modal.Body>
                                            <Modal.Footer onclose={()=> {
                                                self.setState({open: false, selected: ''})
                                            }
                                            } onconfirm={()=> {
                                                console.log(_.union(self.state.form[index].value.split(','),
                                                    self.state.selected.split(',')))
                                                item.onchange(index, _.union(self.state.form[index].value.split(','),
                                                        self.state.selected.split(',')).join(',') + ',')
                                                self.setState({open: false, selected: ''})
                                            }
                                            }/>
                                        </Modal>
                                    </FormItem>
                                } else if (item.type == FormItemType.SELECT) {
                                    return <FormItem {...item} key={index}>
                                        <select className="form-control" onChange={(e)=> {
                                            item.onchange(index, e.target.value)
                                        }}>
                                            {
                                                data_category.list.map(function (item_, index) {
                                                    return <option selected={(item_.id == item.value) ? 'selected' : ''}
                                                                   value={item_.id} key={index}>{item_.name}</option>
                                                })
                                            }
                                        </select>
                                    </FormItem>
                                } else {
                                    return <FormItem index={index} {...item} key={index}></FormItem>
                                }
                            })
                        }
                        <FormGroup>
                            <Label></Label>
                            <InputGroup>
                                <button onClick={self.onsubmit} className="btn btn-success" type="submit">
                                    {Lang.NEWS_CREATE.save}{this.props[PAGE_SUBJECT.NOTICE_ADD].isFetching ? '...' : ''}</button>
                            </InputGroup>
                        </FormGroup>
                    </div>
                </Panel>
            </div>
        )
    }
});
function select(state) {
    return {
        user: state.user.user,
        [md5Url.NOTICE_CATEGORY_FIND]: state.fetchBySubject[md5Url.NOTICE_CATEGORY_FIND],
        [md5Url.NOTICE_ADD]: state.fetchBySubject[md5Url.NOTICE_ADD],
        [PAGE_SUBJECT.NOTICE_ADD]: state.pageBySubject[PAGE_SUBJECT.NOTICE_ADD]
    }
}
export default connect(select)(AddNews)
